﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace MSH.Common.Helpers
{
    /// <summary>
    /// De CommonHelper is verantwoordelijk voor een algemene taken.
    /// </summary>
    public static class CommonHelper
    {
        private static readonly MD5 Md5 = MD5.Create();

        /// <summary>
        /// Geeft de MD5 hash van een gegeven input string
        /// </summary>
        /// <param name="s">Input string</param>
        /// <returns>MD5 hashed string</returns>
        public static string GetMd5Sum(string s)
        {
            byte[] input = Encoding.UTF8.GetBytes(s);
            byte[] result = Md5.ComputeHash(input);
            return Convert.ToBase64String(result);
        }

        /// <summary>
        /// Converteert een gegeven input string naar Base64
        /// </summary>
        /// <param name="s">Input string</param>
        /// <returns>Base64 string</returns>
        public static string StringToBase64(string s)
        {
            try
            {
                byte[] bytes = new byte[s.Length];
                bytes = System.Text.Encoding.UTF8.GetBytes(s);
                return Convert.ToBase64String(bytes);
            }
            catch (Exception e)
            {
                throw new Exception("StringToBase64 error: " + e.Message);
            }
        }

        /// <summary>
        /// Converteert Base64 string naar een string
        /// </summary>
        /// <param name="s">Base64 string</param>
        /// <returns>Omgezette Base64 string</returns>
        static public string Base64ToString(string s)
        {

            byte[] encodedDataAsBytes

                = System.Convert.FromBase64String(s);

            string returnValue = 

               System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);

            return returnValue;

        }
         
        /// <summary>
        /// Maakt vanuit de stream een MD5Hash
        /// </summary>
        /// <param name="stream">Inputstream</param>
        /// <returns>MD5Hash</returns>
        public static string GetMD5HashFromStream(Stream stream)
        {
      
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(stream);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }

    }
}
